from flask import request
from flask import abort
from flask import redirect
from flask import url_for
from functools import wraps
from flask import session
from flask_principal import Principal, Permission,RoleNeed,identity_changed,identity_loaded
from models.entity.token import Token
import datetime




def permission_check(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            token_str=session["auth"]["token"]    # 从g对象中获取token
        except:
            token_str=None
        if token_str is None:
            token_str=request.args.get("token",None)    # 从get参数中获取token
        if token_str is None:
            token_str=request.headers.get("token",default="")    # 从请求头中获取token
        # print("url_root: %s" % request.url_root)
        # print("base_url: %s" % request.base_url)
        in_site_url=request.base_url[len(request.url_root)-1:]
        print(11111111111)
        print("in_site_url: %s" % in_site_url)
        print(session["auth"]["urls"])
        if in_site_url in session["auth"]["urls"]:
            # 该token具有相应权限
            print(333)
            return func(*args, **kwargs)
        print(22222)
        return abort(403)
    return wrapper

def logon_check(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # print("token in session: %s" %str(session["auth"]["token"]))
        try:
            # print("token in session: %s" % str(session["auth"]["token"]))
            token_str=session["auth"]["token"]    # 从session中获取token
            # token_str = session["token"]
            print(111111111111,token_str)
        except:
            token_str=None
        # if token_str is None:
        #     token_str=request.args.get("token",None)    # 从get参数中获取token
        # if token_str is None:
        #     token_str=request.headers.get("token",default="")    # 从请求头中获取token
        if token_str==None:
            # 未登录处理
            # 跳转登录页面
            print("--------------------------------------token is not in the header")
            print("------------------------------------request path: "+request.path)
            return redirect(url_for("user.login"))
        ###我加的保存token_str
        # Token().save()
        # Token.token
        the_token=Token.get_token_by_token_str(token_str=token_str)
        print(22222,the_token)
        if (the_token.create_time+datetime.timedelta(minutes=the_token.exp_time)) < datetime.datetime.utcnow():
            # 如果token已过期
            # 跳转登录页面
            print("----------------------------------token is overdue,跳转到login")
            return redirect(url_for("user.login"))
        if not the_token:
            # 如果token不在数据库中
            print("-------------------------------------token is not in the database")
            return abort(403)
        # 确认登录
        print("------------------------------------login successfully")
        return func(*args, **kwargs)
    return wrapper
